<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="isAdd ? '新建规则' : '编辑规则'"
    width="600px"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input v-model="form.ruleName" maxlength="20" placeholder="请输入规则名称" />
      </el-form-item>

      <el-form-item label="规则关系">
        <el-radio-group v-model="form.ruleType">
          <el-radio :label="1">满足以下任一规则</el-radio>
          <el-radio :label="2">满足以下全部规则</el-radio>
        </el-radio-group>
      </el-form-item>

      <div class="group-head">
        <b>基础规则1： 创建订单数限制</b>
        <el-switch v-model="form.ruleSwitchPlaceOrder" :active-value="1" :inactive-value="0" />
      </div>
      <div class="group-body" v-if="form.ruleSwitchPlaceOrder === 1">
        最近
        <el-input
          v-model="rulePlaceOrderLimit.timeNum"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入小时数"
          style="width: 100px"
        />
        小时，创建订单数
        <el-select v-model="rulePlaceOrderLimit.compare" placeholder="请选择" style="width: 100px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="rulePlaceOrderLimit.num"
          class="mar-l"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入订单数"
          style="width: 100px"
        />
      </div>

      <div class="group-head">
        <b>基础规则2： 待付款订单数限制</b>
        <el-switch v-model="form.ruleSwitchWaitPay" :active-value="1" :inactive-value="0" />
      </div>
      <div class="group-body" v-if="form.ruleSwitchWaitPay === 1">
        最近
        <el-input
          v-model="ruleWaitPayLimit.timeNum"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入小时数"
          style="width: 100px"
        />
        小时，待付款订单数
        <el-select v-model="ruleWaitPayLimit.compare" placeholder="请选择" style="width: 100px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="ruleWaitPayLimit.num"
          class="mar-l"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入订单数"
          style="width: 100px"
        />
      </div>

      <div class="group-head">
        <b>基础规则3： 单sku商品采购数限制</b>
        <el-switch v-model="form.ruleSwitchSku" :active-value="1" :inactive-value="0" />
      </div>
      <div class="group-body" v-if="form.ruleSwitchSku === 1">
        单sku商品采购数量
        <el-select v-model="ruleSkuLimit.compare" placeholder="请选择" style="width: 100px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="ruleSkuLimit.num"
          class="mar-l"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入采购数"
          style="width: 100px"
        />
      </div>

      <div class="group-head">
        <b>基础规则4： 售后订单数限制</b>
        <el-switch v-model="form.ruleSwitchPostSale" :active-value="1" :inactive-value="0" />
      </div>
      <div class="group-body" v-if="form.ruleSwitchPostSale === 1">
        最近
        <el-input
          v-model="rulePostSaleLimit.timeNum"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入月数"
          style="width: 100px"
        />
        个月，售后订单数
        <el-select v-model="rulePostSaleLimit.compare" placeholder="请选择" style="width: 100px">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="rulePostSaleLimit.num"
          class="mar-l"
          onkeyup="value=value.replace(/[^\d]/g,'')"
          maxlength="9"
          placeholder="输入采购数"
          style="width: 100px"
        />
      </div>

      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">已发布</el-radio>
          <el-radio :label="0">未发布</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="doCancel">取消</el-button>
        <el-button type="primary" @click="doSubmit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import { saveRiskRule, updateRiskRule } from '@/api/riskApi'
  import type { RiskRule, RiskRuleSaveParam, RiskRuleUpdateParam } from '@/api/model/riskModel'
  import { ApiStatus } from '@/utils/http/status'

  const props = defineProps<{
    modelValue: boolean
    data?: RiskRule | null
  }>()

  const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }>()

  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  const isAdd = computed(() => !props.data)

  const formRef = ref()

  const form = ref({
    ruleName: '',
    ruleType: 1,
    status: 1,
    ruleSwitchPlaceOrder: 0,
    ruleSwitchPostSale: 0,
    ruleSwitchSku: 0,
    ruleSwitchWaitPay: 0,
    rulePlaceOrderLimit: '',
    rulePostSaleLimit: '',
    ruleSkuLimit: '',
    ruleWaitPayLimit: ''
  })

  const rules = {
    ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }]
  }

  const rulePlaceOrderLimit = ref({
    timeNum: 0,
    compare: 'lt',
    num: 0
  })

  const rulePostSaleLimit = ref({
    timeNum: 0,
    compare: 'lt',
    num: 0
  })

  const ruleSkuLimit = ref({
    compare: 'lt',
    num: 0
  })

  const ruleWaitPayLimit = ref({
    timeNum: 0,
    compare: 'lt',
    num: 0
  })

  const options = ref([
    {
      value: 'lt',
      label: '小于'
    },
    {
      value: 'eq',
      label: '等于'
    },
    {
      value: 'gt',
      label: '大于'
    }
  ])

  // 监听传入的数据变化
  watch(
    () => props.data,
    (newData) => {
      if (newData) {
        // 编辑模式
        form.value = { ...newData }

        // 解析规则限制数据
        if (newData.rulePlaceOrderLimit) {
          try {
            rulePlaceOrderLimit.value = JSON.parse(newData.rulePlaceOrderLimit)
          } catch (e) {
            console.error('解析创建订单数限制失败:', e)
          }
        }

        if (newData.ruleWaitPayLimit) {
          try {
            ruleWaitPayLimit.value = JSON.parse(newData.ruleWaitPayLimit)
          } catch (e) {
            console.error('解析待付款订单数限制失败:', e)
          }
        }

        if (newData.ruleSkuLimit) {
          try {
            ruleSkuLimit.value = JSON.parse(newData.ruleSkuLimit)
          } catch (e) {
            console.error('解析单sku采购数限制失败:', e)
          }
        }

        if (newData.rulePostSaleLimit) {
          try {
            rulePostSaleLimit.value = JSON.parse(newData.rulePostSaleLimit)
          } catch (e) {
            console.error('解析售后订单数限制失败:', e)
          }
        }
      } else {
        // 新增模式，重置数据
        form.value = {
          ruleName: '',
          ruleType: 1,
          status: 1,
          ruleSwitchPlaceOrder: 0,
          ruleSwitchPostSale: 0,
          ruleSwitchSku: 0,
          ruleSwitchWaitPay: 0,
          rulePlaceOrderLimit: '',
          rulePostSaleLimit: '',
          ruleSkuLimit: '',
          ruleWaitPayLimit: ''
        }

        rulePlaceOrderLimit.value = { timeNum: 0, compare: 'lt', num: 0 }
        ruleWaitPayLimit.value = { timeNum: 0, compare: 'lt', num: 0 }
        ruleSkuLimit.value = { compare: 'lt', num: 0 }
        rulePostSaleLimit.value = { timeNum: 0, compare: 'lt', num: 0 }
      }
    },
    { immediate: true }
  )

  function doCancel() {
    visible.value = false
  }

  async function doSubmit() {
    try {
      await formRef.value.validate()

      // 组装规则限制数据
      form.value.rulePlaceOrderLimit = JSON.stringify(rulePlaceOrderLimit.value)
      form.value.ruleWaitPayLimit = JSON.stringify(ruleWaitPayLimit.value)
      form.value.ruleSkuLimit = JSON.stringify(ruleSkuLimit.value)
      form.value.rulePostSaleLimit = JSON.stringify(rulePostSaleLimit.value)

      if (isAdd.value) {
        // 新增
        const saveParam: RiskRuleSaveParam = {
          ruleName: form.value.ruleName,
          ruleType: form.value.ruleType,
          status: form.value.status,
          ruleSwitchPlaceOrder: form.value.ruleSwitchPlaceOrder,
          ruleSwitchWaitPay: form.value.ruleSwitchWaitPay,
          ruleSwitchSku: form.value.ruleSwitchSku,
          ruleSwitchPostSale: form.value.ruleSwitchPostSale,
          rulePlaceOrderLimit: form.value.rulePlaceOrderLimit,
          ruleWaitPayLimit: form.value.ruleWaitPayLimit,
          ruleSkuLimit: form.value.ruleSkuLimit,
          rulePostSaleLimit: form.value.rulePostSaleLimit
        }

        const res = await saveRiskRule(saveParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('新增成功')
          emit('success')
          visible.value = false
        } else {
          ElMessage.error(res.message || '新增失败')
        }
      } else {
        // 编辑
        const updateParam: RiskRuleUpdateParam = {
          id: props.data!.id!,
          ruleName: form.value.ruleName,
          ruleType: form.value.ruleType,
          status: form.value.status,
          ruleSwitchPlaceOrder: form.value.ruleSwitchPlaceOrder,
          ruleSwitchWaitPay: form.value.ruleSwitchWaitPay,
          ruleSwitchSku: form.value.ruleSwitchSku,
          ruleSwitchPostSale: form.value.ruleSwitchPostSale,
          rulePlaceOrderLimit: form.value.rulePlaceOrderLimit,
          ruleWaitPayLimit: form.value.ruleWaitPayLimit,
          ruleSkuLimit: form.value.ruleSkuLimit,
          rulePostSaleLimit: form.value.rulePostSaleLimit
        }

        const res = await updateRiskRule(updateParam)
        if (res.code === ApiStatus.success) {
          ElMessage.success('更新成功')
          emit('success')
          visible.value = false
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      }
    } catch (error) {
      console.error('提交表单失败:', error)
    }
  }
</script>

<style lang="scss" scoped>
  .group-head {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
  }

  .group-body {
    margin-bottom: 20px;
    padding: 10px;
    background-color: var(--art-gray-100);
    border-radius: 4px;

    .el-input,
    .el-select {
      width: 100px;
      margin: 0 5px;

      :deep(.el-input__inner) {
        height: 32px;
        line-height: 32px;
      }
    }

    .mar-l {
      margin-left: 10px;
    }
  }

  .dialog-footer {
    text-align: right;
  }
</style>
